<html><head><meta charset="utf-8"><title> 17 Webpack 优化之体积优化-慕课专栏</title>
			<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
			<meta name="renderer" content="webkit">
			<meta property="qc:admins" content="77103107776157736375">
			<meta property="wb:webmaster" content="c4f857219bfae3cb">
			<meta http-equiv="Access-Control-Allow-Origin" content="*">
			<meta http-equiv="Cache-Control" content="no-transform ">
			<meta http-equiv="Cache-Control" content="no-siteapp">
			<link rel="apple-touch-icon" sizes="76x76" href="https://www.imooc.com/static/img/common/touch-icon-ipad.png">
			<link rel="apple-touch-icon" sizes="120x120" href="https://www.imooc.com/static/img/common/touch-icon-iphone-retina.png">
			<link rel="apple-touch-icon" sizes="152x152" href="https://www.imooc.com/static/img/common/touch-icon-ipad-retina.png">
			<link href="https://moco.imooc.com/captcha/style/captcha.min.css" rel="stylesheet">
			<link rel="stylesheet" href="https://www.imooc.com/static/moco/v1.0/dist/css/moco.min.css?t=201907021539" type="text/css">
			<link rel="stylesheet" href="https://www.imooc.com/static/lib/swiper/swiper-3.4.2.min.css?t=201907021539">
			<link rel="stylesheet" href="https://static.mukewang.com/static/css/??base.css,common/common-less.css?t=2.5,column/zhuanlanChapter-less.css?t=2.5,course/inc/course_tipoff-less.css?t=2.5?v=201907051055" type="text/css">
			<link charset="utf-8" rel="stylesheet" href="https://www.imooc.com/static/lib/ueditor/themes/imooc/css/ueditor.css?v=201907021539"><link rel="stylesheet" href="https://www.imooc.com/static/lib/baiduShare/api/css/share_style0_16.css?v=6aba13f0.css"></head>
			<body><div id="main">

<div class="container clearfix" id="top" style="display: block; width: 1134px;">
    
    <div class="center_con js-center_con l" style="width: 1134px;">
        <div class="article-con">
                            <!-- 买过的阅读 -->
                <div class="map">
                    <a href="/read" target="_blank"><i class="imv2-feather-o"></i></a>
                    <a href="/read/29" target="_blank">Webpack 从零入门到工程化实战</a>
                    <a href="" target="_blank">
                        <span>
                            / 3-1  17 Webpack 优化之体积优化
                        </span>
                    </a>
                </div>

            


            <div class="art-title" style="margin-top: 0px;">
                 17 Webpack 优化之体积优化
            </div>
            <div class="art-info">
                
                <span>
                    更新时间：2019-06-24 09:30:27
                </span>
            </div>
            <div class="art-top">
                                <img src="https://img.mukewang.com/5cd963de0001b93006400360.jpg" alt="">
                                                <div class="famous-word-box">
                    <img src="https://www.imooc.com/static/img/column/bg-l.png" alt="" class="bg1 bg">
                    <img src="https://www.imooc.com/static/img/column/bg-r.png" alt="" class="bg2 bg">
                    <div class="famous-word">自信和希望是青年的特权。<p class="author">——大仲马</p></div>
                </div>
                            </div>
            <div class="art-content js-lookimg">
                <div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">Webpack 毕竟是个项目打包工具，一般 web 项目，打完包之后，需要发布到服务器上供用户使用，受带宽的限制，我们的项目体积需要越小越好，所以 Webpack 中打包的体积是 Webpack 中重要的一环，本小节内容将从 JavaScript、CSS 和其他静态资源体积优化入手，介绍项目的体积优化方案。</p>
</div><div class="cl-preview-section"><h2 id="javascript-压缩" style="font-size: 30px;">JavaScript 压缩</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在<code>mode=production</code>下，Webpack 会自动压缩代码，我们可以自定义自己的压缩工具，这里推荐 <a href="https://github.com/webpack-contrib/terser-webpack-plugin">terser-webpack-plugin</a>，它是 Webpack 官方维护的插件，使用<a href="https://github.com/terser-js/terser">terser</a>来压缩 JavaScript 代码。UglifyJS 在压缩 ES5 方面做的很优秀，但是随着 ES6 语法的普及，UglifyJS 在 ES6 代码压缩上做的不够好，所以有了<code>uglify-es</code>项目，但是之后<code>uglify-es</code>项目不在维护了，terser 是从<code>uglify-es</code>项目拉的一个分支，来继续维护。terser-webpack-plugin 具有跟 Uglifyjs-webpack-plugin 相同的参数，我们在 Webpack 中可以通过配置文件直接调用：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token keyword">const</span> TerserPlugin <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'terser-webpack-plugin'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

module<span class="token punctuation">.</span>exports <span class="token operator">=</span> <span class="token punctuation">{</span>
    optimization<span class="token punctuation">:</span> <span class="token punctuation">{</span>
        minimizer<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token keyword">new</span> <span class="token class-name">TerserPlugin</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">]</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在实际开发中，我们可以通过移出一些不用的代码从而达到优化代码体积的作用，Tree-Shaking 也是依赖这个插件的：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token keyword">new</span> <span class="token class-name">TerserPlugin</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    <span class="token comment">// 使用 cache，加快二次构建速度</span>
    cache<span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
    terserOptions<span class="token punctuation">:</span> <span class="token punctuation">{</span>
        comments<span class="token punctuation">:</span> <span class="token boolean">false</span><span class="token punctuation">,</span>
        compress<span class="token punctuation">:</span> <span class="token punctuation">{</span>
            <span class="token comment">// 删除无用的代码</span>
            unused<span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
            <span class="token comment">// 删掉 debugger</span>
            drop_debugger<span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span> <span class="token comment">// eslint-disable-line</span>
            <span class="token comment">// 移除 console</span>
            drop_console<span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span> <span class="token comment">// eslint-disable-line</span>
            <span class="token comment">// 移除无用的代码</span>
            dead_code<span class="token punctuation">:</span> <span class="token boolean">true</span> <span class="token comment">// eslint-disable-line</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">压缩是发布前处理最耗时间的一个步骤，在 Webpack 配置中可以通过开启 terser-webpack-plugin 的多线程压缩来加速我们的构建压缩速度：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token keyword">const</span> TerserPlugin <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'terser-webpack-plugin'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

module<span class="token punctuation">.</span>exports <span class="token operator">=</span> <span class="token punctuation">{</span>
  optimization<span class="token punctuation">:</span> <span class="token punctuation">{</span>
    minimizer<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token keyword">new</span> <span class="token class-name">TerserPlugin</span><span class="token punctuation">(</span>
      parallel<span class="token punctuation">:</span> <span class="token boolean">true</span>   <span class="token comment">// 多线程</span>
    <span class="token punctuation">)</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><h3 id="其他代码级别优化技巧">其他代码级别优化技巧</h3>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">合理划分代码职责，适当使用按需加载方案；</li>
<li style="font-size: 20px; line-height: 38px;">善用 webpack-bundle-analyzer 插件，帮助分析 Webpack 打包后的模块依赖关系；</li>
<li style="font-size: 20px; line-height: 38px;">设置合理的 SplitChunks 分组；</li>
<li style="font-size: 20px; line-height: 38px;">对于一些 UI 组件库，例如 AntDesign、ElementUI 等，可以使用<a href="https://github.com/ant-design/babel-plugin-import">bable-plugin-import</a>这类工具进行优化；</li>
<li style="font-size: 20px; line-height: 38px;">使用 lodash、momentjs 这类库，不要一股脑引入，要按需引入，momentjs 可以用 date-fns 库来代替；</li>
<li style="font-size: 20px; line-height: 38px;">合理使用 hash 占位符，防止 hash 重复出现，导致文件名变化从而 HTTP 缓存过期；</li>
<li style="font-size: 20px; line-height: 38px;">合理使用 polyfill，防止多余的代码；</li>
<li style="font-size: 20px; line-height: 38px;">使用 ES6 语法，尽量不使用具有副作用的代码，以加强 Tree-Shaking 的效果；</li>
<li style="font-size: 20px; line-height: 38px;">使用 Webpack 的 Scope Hoisting（作用域提升）功能。</li>
</ol>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">Tips：其实 webpack 4 中，在 production 模式下已经根据大多数项目的优化经验做了通用的配置，类似 Tree-Shaking、Scope Hoisting 都是默认开启的，而且最新版本的 Webpack 使用的压缩工具就是 terser-webpack-plugin。</p>
</blockquote>
</div><div class="cl-preview-section"><h3 id="什么是-scope-hoisting">什么是 Scope Hoisting</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">作用域提升（Scope Hoisting）是指 webpack 通过 ES6 语法的静态分析，分析出模块之间的依赖关系，尽可能地把模块放到同一个函数中。下面通过代码示例来理解：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// utils.js</span>
<span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token string">'Hello, Webpack'</span><span class="token punctuation">;</span>
<span class="token comment">// entry.js</span>
<span class="token keyword">import</span> str <span class="token keyword">from</span> <span class="token string">'./util.js'</span><span class="token punctuation">;</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">普通打包后，<code>utils.js</code>的内容和<code>entry.js</code>会分开，例如下面代码：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span>module<span class="token punctuation">,</span> __webpack_exports__<span class="token punctuation">,</span> __webpack_require__<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">var</span> __WEBPACK_IMPORTED_MODULE_0__util_js__ <span class="token operator">=</span> <span class="token function">__webpack_require__</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>__WEBPACK_IMPORTED_MODULE_0__util_js__<span class="token punctuation">[</span><span class="token string">'a'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token keyword">function</span><span class="token punctuation">(</span>module<span class="token punctuation">,</span> __webpack_exports__<span class="token punctuation">,</span> __webpack_require__<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        __webpack_exports__<span class="token punctuation">[</span><span class="token string">'a'</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token string">'Hello, Webpack'</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">通过配置 webpack 4 的<code>optimization.concatenateModules=true</code>：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// webpack.config.js</span>
module<span class="token punctuation">.</span>exports <span class="token operator">=</span> <span class="token punctuation">{</span>
    optimization<span class="token punctuation">:</span> <span class="token punctuation">{</span>
        concatenateModules<span class="token punctuation">:</span> <span class="token boolean">true</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这样就开启了 Scope Hoisting，这时候打包变成了：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span>module<span class="token punctuation">,</span> __webpack_exports__<span class="token punctuation">,</span> __webpack_require__<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">var</span> util <span class="token operator">=</span> <span class="token string">'Hello, Webpack'</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>util<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们发现<code>utils.js</code>内容和<code>entry.js</code>的内容合并在一起了！所以通过 Scope Hoisting 的功能可以让 Webpack 打包出来的代码文件更小、运行的更快。</p>
</div><div class="cl-preview-section"><h2 id="css" style="font-size: 30px;">CSS</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">除了 JavaScript 外，样式文件也是前端中重要的资源，Webpack 本身是 JavaScript 的打包器，在 CSS 方面通过强大的插件社区，可以实现 CSS 的优化。</p>
</div><div class="cl-preview-section"><h3 id="css-导出">CSS 导出</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">首先我们的 CSS 文件应该是导出到单独的 CSS 文件中，而不要直接打包到 JavaScript 文件中，然后通过<code>style-loader</code>的 <code>addStyles</code>方法添加进去，导出 CSS 文件就需要使用<a href="https://github.com/webpack-contrib/mini-css-extract-plugin">mini-css-extract-plugin</a>这个插件。</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token keyword">const</span> MiniCssExtractPlugin <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'mini-css-extract-plugin'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
module<span class="token punctuation">.</span>exports <span class="token operator">=</span> <span class="token punctuation">{</span>
    plugins<span class="token punctuation">:</span> <span class="token punctuation">[</span>
        <span class="token keyword">new</span> <span class="token class-name">MiniCssExtractPlugin</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
            filename<span class="token punctuation">:</span> <span class="token string">'[name].css'</span><span class="token punctuation">,</span>
            chunkFilename<span class="token punctuation">:</span> <span class="token string">'[name].[contenthash:8].css'</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token punctuation">]</span><span class="token punctuation">,</span>
    module<span class="token punctuation">:</span> <span class="token punctuation">{</span>
        rules<span class="token punctuation">:</span> <span class="token punctuation">[</span>
            <span class="token punctuation">{</span>
                test<span class="token punctuation">:</span> <span class="token regex">/\.css$/</span><span class="token punctuation">,</span>
                use<span class="token punctuation">:</span> <span class="token punctuation">[</span>
                    <span class="token punctuation">{</span>
                        loader<span class="token punctuation">:</span> MiniCssExtractPlugin<span class="token punctuation">.</span>loader<span class="token punctuation">,</span>
                        options<span class="token punctuation">:</span> <span class="token punctuation">{</span>
                            publicPath<span class="token punctuation">:</span> <span class="token string">'../'</span><span class="token punctuation">,</span>
                            hmr<span class="token punctuation">:</span> process<span class="token punctuation">.</span>env<span class="token punctuation">.</span>NODE_ENV <span class="token operator">===</span> <span class="token string">'development'</span>
                        <span class="token punctuation">}</span>
                    <span class="token punctuation">}</span><span class="token punctuation">,</span>
                    <span class="token string">'css-loader'</span>
                <span class="token punctuation">]</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">]</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">还记得 CSS 章节介绍的<code>contenthash</code>吗，在 CSS 中推荐使用<code>[contenthash]</code>这个占位符做文件的 hash 算法。</p>
</div><div class="cl-preview-section"><h3 id="css-压缩：cssnano">CSS 压缩：cssnano</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><a href="https://cssnano.co/">cssnano</a>是基于 postcss 的一款功能强大的插件包，它集成了 30 多个插件，只需要执行一个命令，就可以对我们的 CSS 做多方面不同类型的优化，比如：</p>
</div><div class="cl-preview-section"><ul>
<li style="font-size: 20px; line-height: 38px;">删除空格和最后一个分号；</li>
<li style="font-size: 20px; line-height: 38px;">删除注释；</li>
<li style="font-size: 20px; line-height: 38px;">优化字体权重；</li>
<li style="font-size: 20px; line-height: 38px;">丢弃重复的样式规则；</li>
<li style="font-size: 20px; line-height: 38px;">压缩选择器；</li>
<li style="font-size: 20px; line-height: 38px;">减少手写属性；</li>
<li style="font-size: 20px; line-height: 38px;">合并规则；</li>
<li style="font-size: 20px; line-height: 38px;">…</li>
</ul>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们来看个 cssnano 处理之前和处理之后的 CSS 内容就能体会到 cssnano 的强大功能了：</p>
</div><div class="cl-preview-section"><pre class="  language-css"><code class="prism  language-css"><span class="token comment">/* input */</span>
<span class="token selector"><span class="token class">.a</span> </span><span class="token punctuation">{</span>
    <span class="token property">background</span><span class="token punctuation">:</span> red<span class="token punctuation">;</span>
    <span class="token property">color</span><span class="token punctuation">:</span> yellow<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token selector"><span class="token class">.b</span> </span><span class="token punctuation">{</span>
    <span class="token property">font-size</span><span class="token punctuation">:</span> bolder<span class="token punctuation">;</span>
    <span class="token property">background</span><span class="token punctuation">:</span> red<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token selector"><span class="token class">.c</span> </span><span class="token punctuation">{</span>
    <span class="token property">color</span><span class="token punctuation">:</span> yellow<span class="token punctuation">;</span>
    <span class="token property">text-align</span><span class="token punctuation">:</span> center<span class="token punctuation">;</span>
    <span class="token property">font-size</span><span class="token punctuation">:</span> bolder<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token selector"><span class="token class">.d</span> </span><span class="token punctuation">{</span>
    <span class="token property">display</span><span class="token punctuation">:</span> flex<span class="token punctuation">;</span>
    <span class="token property">text-align</span><span class="token punctuation">:</span> center<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token comment">/* output */</span>
<span class="token selector"><span class="token class">.a</span> </span><span class="token punctuation">{</span>
    <span class="token property">color</span><span class="token punctuation">:</span> <span class="token hexcode">#ff0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token selector"><span class="token class">.a</span>,
<span class="token class">.b</span> </span><span class="token punctuation">{</span>
    <span class="token property">background</span><span class="token punctuation">:</span> red<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token selector"><span class="token class">.b</span>,
<span class="token class">.c</span> </span><span class="token punctuation">{</span>
    <span class="token property">font-size</span><span class="token punctuation">:</span> bolder<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token selector"><span class="token class">.c</span> </span><span class="token punctuation">{</span>
    <span class="token property">color</span><span class="token punctuation">:</span> <span class="token hexcode">#ff0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token selector"><span class="token class">.c</span>,
<span class="token class">.d</span> </span><span class="token punctuation">{</span>
    <span class="token property">text-align</span><span class="token punctuation">:</span> center<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token selector"><span class="token class">.d</span> </span><span class="token punctuation">{</span>
    <span class="token property">display</span><span class="token punctuation">:</span> flex<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">通过观察上面输入和输出的内容差异，我们发现 cssnano 很智能，它能够将 CSS 规则相同的选择器进行合并，并且还能够将<code>color</code>进行任意的切换，这样的意义是为了缩短实际的字符串长度。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在 Webapck 中，css-loader 已经集成了 cssnano，我们还可以使用<a href="https://github.com/NMFR/optimize-css-assets-webpack-plugin">optimize-css-assets-webpack-plugin</a>来自定义 cssnano 的规则。optimize-css-assets-webpack-plugin 是一个 CSS 的压缩插件，默认的压缩引擎就是 cssnano。我们来看下怎么在 Webpack 中使用这个插件：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// webpack.config.js</span>
<span class="token keyword">const</span> OptimizeCssAssetsPlugin <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'optimize-css-assets-webpack-plugin'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
module<span class="token punctuation">.</span>exports <span class="token operator">=</span> <span class="token punctuation">{</span>
    plugins<span class="token punctuation">:</span> <span class="token punctuation">[</span>
        <span class="token keyword">new</span> <span class="token class-name">OptimizeCssAssetsPlugin</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
            assetNameRegExp<span class="token punctuation">:</span> <span class="token regex">/\.optimize\.css$/g</span><span class="token punctuation">,</span>
            cssProcessor<span class="token punctuation">:</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'cssnano'</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token comment">// 这里制定了引擎，不指定默认也是 cssnano</span>
            cssProcessorPluginOptions<span class="token punctuation">:</span> <span class="token punctuation">{</span>
                preset<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">'default'</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>discardComments<span class="token punctuation">:</span> <span class="token punctuation">{</span>removeAll<span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">]</span>
            <span class="token punctuation">}</span><span class="token punctuation">,</span>
            canPrint<span class="token punctuation">:</span> <span class="token boolean">true</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token punctuation">]</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">optimize-css-assets-webpack-plugin 插件默认的 cssnano 配置已经做的很友好了，不需要额外的配置就可以达到最佳效果。</p>
</div><div class="cl-preview-section"><h2 id="图片资源优化" style="font-size: 30px;">图片资源优化</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">通常我们的代码体积会比图片体积小很多，有的时候整个页面的代码都不如一张头图大。好在图片资源不会阻塞浏览器渲染，但是不合理的图片大小也会消耗一定的代码。在之前章节中也已经提到使用：url-loader、svg-url-loader 和 image-webpack-loader 来优化图片，还介绍了使用雪碧图来优化图片资源。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><a href="https://github.com/webpack-contrib/url-loader">url-loader</a> 可以按照配置将小于一定体积的静态文件内联进我们的应用。当我们指定了 <code>limit</code> 这个 <code>options</code> 选项，它会将文件编码成比无配置更小的 <a href="https://css-tricks.com/data-uris/">Base64 的数据 url</a> 并将该 url 返回，这样可以将图片内联进 JavaScript 代码中，并节省一次 HTTP 请求。<a href="https://github.com/bhovhannes/svg-url-loader">svg-url-loader</a> 的工作原理类似于 url-loader，除了它利用 <a href="https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding">URL encoding</a> 而不是 Base64 对文件编码，对于 SVG 图片来说，svg-url-loader 的这种方式这是有效的，因为 SVG 文件本质上是纯文本文件，这种 URL encoding 编码规模效应更加明显。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">如果我们的项目中小图片特别多，例如有很多 icon 类的图标，这时候则推荐使用<a href="https://developer.mozilla.org/zh-CN/docs/Web/Guide/CSS/CSS_Image_Sprites">雪碧图</a>（CSS Sprite）来合并这些小图到一张大图中，然后使用<code>background-position</code>来设置图片的位置，通过这样的方式可以节省多次小图片的请求。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">对于大图片来说，可以使用<a href="https://github.com/tcoopman/image-webpack-loader">image-webpack-loader</a>来压缩图片，image-webpack-loader 它支持 JPG、PNG、GIF 和 SVG 格式的图片，因此我们在碰到所有这些类型的图片都会使用它。</p>
</div><div class="cl-preview-section"><h2 id="总结" style="font-size: 30px;">总结</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">本小节是 Webpack 优化的第一篇文章，本文从体积优化方面入手，分别从前端项目中最常见的 JavaScript、CSS 和图片三部分入手，介绍了各自的优化方案，希望对大家项目的实际应用中有所帮助。</p>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">本小节 Webpack 相关面试题：</p>
<p style="font-size: 20px; line-height: 38px;">本章节一直在回答一个问题：webpack 怎么优化。本小节主要从减少代码体积方面来介绍 Webpack 优化方案。</p>
</blockquote>
</div></div>
            </div>
                            <!-- 买过的阅读 -->
                <div class="art-next-prev clearfix">
                                                                        <!-- 已买且开放 或者可以试读 -->
                            <a href="/read/29/article/274">
                                                    <div class="prev l clearfix">
                                <div class="icon l">
                                    <i class="imv2-arrow3_l"></i>
                                </div>
                                <p>
                                     16 Webpack 环境相关配置及配置文件拆分
                                </p>
                            </div>
                        </a>
                                                                                            <!-- 已买且开放 或者可以试读 -->
                            <a href="/read/29/article/276">
                                                    <div class="next r clearfix">
                                <p>
                                    18 Webpack 优化之增强缓存命中率
                                </p>
                                <div class="icon r">
                                    <i class="imv2-arrow3_r"></i>
                                </div>

                            </div>
                        </a>
                                    </div>
                    </div>
        <div class="comments-con js-comments-con" id="coments_con">
        </div>



    </div>
    
    
    

</div>
 
<!-- 专栏介绍页专栏评价 -->

<!-- 专栏介绍页底部三条评价 -->

<!-- 专栏阅读页弹层目录和介绍页页面目录 -->

<!-- 专栏阅读页发布回复 -->

<!-- 专栏阅读页发布评论 -->

<!-- 专栏阅读页底部评论 -->

<!-- 专栏阅读 单个 评论 -->

<!-- 新增回复和展开三条以外回复 -->

<!-- 立即订阅的弹窗 -->












</div></body></html>